package info.niwota.home.fm;

import info.niwota.home.R;
import instant.openvfs.home.Debug;

import java.util.ArrayList;

import android.app.Activity;
import android.appwidget.AppWidgetHost;
import android.appwidget.AppWidgetHostView;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProviderInfo;
import android.content.Intent;
import android.os.Bundle;
import android.os.Parcelable;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.Window;
import android.widget.LinearLayout;

public class WidgetViewActivity extends Activity {
	private static final int APPWIDGET_HOST_ID = 10240;

	private static final String EXTRA_CUSTOM_WIDGET = "custom_widget";

	private static final String LOG_TAG = "WidgetViewActivity";

	private static final int REQUEST_CREATE_APPWIDGET = 5;

	private static final int REQUEST_PICK_APPWIDGET = 9;

	private static final String SEARCH_WIDGET = "search_widget";

	private AppWidgetHost mAppWidgetHost;

	private AppWidgetManager mAppWidgetManager;

	private AppWidgetHostView widget;

	void addAppWidget(Intent data) {
		int appWidgetId = data.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID,
				-1);
		String customWidget = data.getStringExtra(EXTRA_CUSTOM_WIDGET);
		if (SEARCH_WIDGET.equals(customWidget)) {
			mAppWidgetHost.deleteAppWidgetId(appWidgetId);
			// add search
		} else {
			AppWidgetProviderInfo appWidget = mAppWidgetManager
					.getAppWidgetInfo(appWidgetId);
			if (appWidget.configure != null) {
				Intent intent = new Intent(
						AppWidgetManager.ACTION_APPWIDGET_CONFIGURE);
				intent.setComponent(appWidget.configure);
				intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID,
						appWidgetId);

				startActivityForResult(intent, REQUEST_CREATE_APPWIDGET);
			} else {
				onActivityResult(REQUEST_CREATE_APPWIDGET, Activity.RESULT_OK,
						data);
			}
		}
	}

	private void completeAddAppWidget(Intent data) {
		Bundle extras = data.getExtras();
		int appWidgetId = extras
				.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID, -1);
		if (Debug.DEBUG) {
			Log.d(LOG_TAG, "completeAddAppWidget extras=" + extras);
		}

		AppWidgetProviderInfo appWidgetInfo = mAppWidgetManager
				.getAppWidgetInfo(appWidgetId);

		LinearLayout v = (LinearLayout) findViewById(R.id.widgetview_panel);
		if (widget != null) {
			int id = widget.getAppWidgetId();
			mAppWidgetHost.deleteAppWidgetId(id);
		}
		v.removeAllViews();
		widget = mAppWidgetHost.createView(this, appWidgetId, appWidgetInfo);
		v.addView(widget);

		setTitle(appWidgetInfo.label);
		getWindow().setFeatureDrawableResource(Window.FEATURE_LEFT_ICON,
				appWidgetInfo.icon);
	}

	protected void doPick() {
		int appWidgetId = mAppWidgetHost.allocateAppWidgetId();

		Intent pickIntent = new Intent(AppWidgetManager.ACTION_APPWIDGET_PICK);
		pickIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
		// add the search widget
		ArrayList<AppWidgetProviderInfo> customInfo = new ArrayList<AppWidgetProviderInfo>();
		// AppWidgetProviderInfo info = new AppWidgetProviderInfo();
		// info.provider = new ComponentName(getPackageName(), "XXX.YYY");
		// info.label = getString(R.string.group_search);
		// info.icon = R.drawable.ic_search_widget;
		// customInfo.add(info);
		pickIntent.putParcelableArrayListExtra(
				AppWidgetManager.EXTRA_CUSTOM_INFO, customInfo);
		ArrayList<Bundle> customExtras = new ArrayList<Bundle>();
		// Bundle b = new Bundle();
		// b.putString(EXTRA_CUSTOM_WIDGET, SEARCH_WIDGET);
		// customExtras.add(b);
		pickIntent.putParcelableArrayListExtra(
				AppWidgetManager.EXTRA_CUSTOM_EXTRAS, customExtras);
		// start the pick activity
		startActivityForResult(pickIntent, REQUEST_PICK_APPWIDGET);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (Debug.DEBUG) {
			Log.d(LOG_TAG, "onActivityResult: " + requestCode + " "
					+ resultCode + "=" + RESULT_OK + " data: " + data);
		}
		if (resultCode == RESULT_OK) {
			switch (requestCode) {
			case REQUEST_PICK_APPWIDGET:
				addAppWidget(data);
				break;
			case REQUEST_CREATE_APPWIDGET:
				completeAddAppWidget(data);
				break;
			}
		} else if (requestCode == REQUEST_PICK_APPWIDGET
				&& resultCode == RESULT_CANCELED && data != null) {
			// Clean up the appWidgetId if we canceled
			int appWidgetId = data.getIntExtra(
					AppWidgetManager.EXTRA_APPWIDGET_ID, -1);
			if (appWidgetId != -1) {
				mAppWidgetHost.deleteAppWidgetId(appWidgetId);
			}
		}
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		requestWindowFeature(Window.FEATURE_LEFT_ICON);

		setContentView(R.layout.widgetview);
		//
		mAppWidgetManager = AppWidgetManager.getInstance(this);
		mAppWidgetHost = new AppWidgetHost(this, APPWIDGET_HOST_ID);
		mAppWidgetHost.startListening();
		//
		setTitle("Widget View");
		//
		checkIntent(savedInstanceState);
	}

	private void checkIntent(Bundle savedInstanceState) {
		Intent my = getIntent();
		Parcelable p = my.getParcelableExtra("appwidget_intent");
		if (p != null) {
			if (Debug.DEBUG) {
				Log.d(LOG_TAG, "checkIntent Parcelable: " + p);
			}
			try {
				Intent data = (Intent) p;
				int appWidgetId = mAppWidgetHost.allocateAppWidgetId();
				mAppWidgetManager.bindAppWidgetId(appWidgetId, data
						.getComponent());
				data.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
				onActivityResult(REQUEST_CREATE_APPWIDGET, Activity.RESULT_OK,
						data);
			} catch (SecurityException e) {
				//not granted permission
				//show pick list
				doPick();
			} catch (Exception e) {
				e.printStackTrace();
				// 
			}
		}
		int appWidgetId = my.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID,
				-1);
		if (appWidgetId != -1) {
			if (Debug.DEBUG) {
				Log.d(LOG_TAG, "checkIntent appWidgetId: " + appWidgetId);
			}
			addAppWidget(my);
		}
	}

	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add(0, REQUEST_PICK_APPWIDGET, 0, "Pick Widget");
		return true;
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		try {
			mAppWidgetHost.stopListening();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case REQUEST_PICK_APPWIDGET:
			doPick();
			return true;
		}
		return false;
	}
}